package com.hcy.mqapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hcy.mqbusiness.mqcenterfororder.RocketMqAsyncProducer;
import com.hcy.mqbusiness.mqcenterfororder.RocketMqDelayProducer;
import com.hcy.mqbusiness.mqcenterfororder.RocketMqSyncProducer;
import com.hcy.mqmodel.dto.request.MessageListRequestDTO;
import com.hcy.mqmodel.dto.request.PushOrderRequestDTO;
import com.hcy.mqmodel.dto.request.PushSyncMessageRequestDTO;
import com.hcy.rabbitbasicmodel.enums.Code;
import com.hcy.rabbitbasicmodel.model.ResponseData;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @Author huchenying
 * @Description
 * @Date 2022/3/15 14:33
 */
@RestController
@RequestMapping("/runtime")
public class PushRuntimeController {

    private static final Logger logger = LoggerFactory.getLogger(PushRuntimeController.class);

    @Autowired
    private RocketMqSyncProducer syncProducer;
    @Autowired
    private RocketMqAsyncProducer asyncProducer;
    @Autowired
    private RocketMqDelayProducer delayProducer;

    /**
     * @Author huchenying
     * @Description 接受下单请求消息
     * @Date 2022/3/15 14:34
     **/
    @PostMapping("/pushSyncOrder")
    public ResponseData<SendResult> pushSyncOrder(@Validated @RequestBody PushOrderRequestDTO requestDTO) {
        logger.info("pushSyncOrder start param -> {}", ToStringBuilder.reflectionToString(requestDTO));
        ResponseData<SendResult> responseData = new ResponseData<>();
        try {
            Message message = new Message();
            message.setKeys(requestDTO.getOrderNumber());
            message.setTopic(requestDTO.getTopic());
            if (requestDTO.getTags() != null && requestDTO.getTags().length > 1) {
                StringBuilder stringBuilder = new StringBuilder();
                for (String tag : requestDTO.getTags()) {
                    stringBuilder.append(tag).append(",");
                }
                message.setTags(stringBuilder.toString());
            }
            message.setBody(JSON.toJSONString(requestDTO).getBytes());
            responseData = syncProducer.sendSyncMessage(message);
        } catch (Exception e) {
            logger.info("pushSyncOrder 异常", e);
            responseData.setMsg("消息推送失败");
            responseData.setCode(Code.Success);
            return responseData;
        }
        logger.info("SendResult -> {}", ToStringBuilder.reflectionToString(responseData));
        return responseData;
    }

    /**
     * @Author huchenying
     * @Description 接受延迟消息发送请求
     * @Date 2022/3/15 14:34
     **/
    @PostMapping("/pushSyncDelayOrder")
    public ResponseData<SendResult> pushSyncDelayOrder(@Validated @RequestBody PushOrderRequestDTO requestDTO) {
        logger.info("pushSyncDelayOrder start param -> {}", ToStringBuilder.reflectionToString(requestDTO));
        ResponseData<SendResult> responseData = new ResponseData<>();
        try {
            Message message = new Message();
            message.setKeys(requestDTO.getOrderNumber());
            message.setTopic(requestDTO.getTopic());
            if (requestDTO.getTags() != null && requestDTO.getTags().length > 1) {
                StringBuilder stringBuilder = new StringBuilder();
                for (String tag : requestDTO.getTags()) {
                    stringBuilder.append(tag).append(",");
                }
                message.setTags(stringBuilder.toString());
            }
            message.setBody(JSON.toJSONString(requestDTO).getBytes());
            if (requestDTO.getLevel() == null) {
                logger.warn("延迟等级未设置。。");
                message.setDelayTimeLevel(5);
            } else {
                //1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h 1d 从1开始
                message.setDelayTimeLevel(requestDTO.getLevel());
            }
            responseData = delayProducer.sendSyncMessage(message);
        } catch (Exception e) {
            logger.info("pushDelaySyncOrder 异常", e);
            responseData.setMsg("消息推送失败");
            responseData.setCode(Code.Success);
            return responseData;
        }
        logger.info("SendResult -> {}", ToStringBuilder.reflectionToString(responseData));
        return responseData;
    }

    /**
     * @Author huchenying
     * @Description 推送同步消息
     * @Date 2022/3/19 21:29
     **/
    @PostMapping("/pushSyncMessage")
    public ResponseData<SendResult> pushSyncMessage(@Validated @RequestBody PushSyncMessageRequestDTO requestDTO){
        logger.info("pushSyncMessage start param -> {}",ToStringBuilder.reflectionToString(requestDTO));
        ResponseData<SendResult> responseData = new ResponseData<>();
        try {
            Message message = new Message();
            message.setTopic(requestDTO.getTopic());
            if (requestDTO.getTags() != null && requestDTO.getTags().length > 1) {
                StringBuilder stringBuilder = new StringBuilder();
                for (String tag : requestDTO.getTags()) {
                    stringBuilder.append(tag).append("||");
                }
                message.setTags(stringBuilder.toString());
            }
            message.setBody(JSON.toJSONString(requestDTO).getBytes());
            responseData = syncProducer.sendSyncMessage(message);
        } catch (Exception e) {
            logger.info("pushSyncMessage 异常", e);
            responseData.setMsg("消息推送失败");
            responseData.setCode(Code.Success);
            return responseData;
        }
        logger.info("SendResult -> {}", ToStringBuilder.reflectionToString(responseData));
        return responseData;
    }
    /**
     * @Author huchenying
     * @Description 推送同步消息
     * @Date 2022/3/19 21:29
     **/
    @PostMapping("/pushSyncMessage0")
    public ResponseData<SendResult> pushSyncMessage0(@Validated @RequestBody Message message){
        logger.info("pushSyncMessage start param -> {}",ToStringBuilder.reflectionToString(message));
        ResponseData<SendResult> responseData = new ResponseData<>();
        try {
            responseData = syncProducer.sendSyncMessage(message);
        } catch (Exception e) {
            logger.info("pushSyncMessage 异常", e);
            responseData.setMsg("消息推送失败");
            responseData.setCode(Code.Success);
            return responseData;
        }
        logger.info("SendResult -> {}", ToStringBuilder.reflectionToString(responseData));
        return responseData;
    }

    /**
     * @Author huchenying
     * @Description 推送异步消息
     * @Date 2022/3/19 21:29
     **/
    @PostMapping("/pushAsyncMessage")
    public ResponseData<SendResult> pushAsyncMessage(@Validated @RequestBody Message message){
        logger.info("pushAsyncMessage start param -> {}",ToStringBuilder.reflectionToString(message));
        ResponseData<SendResult> responseData = new ResponseData<>();
        try {
            asyncProducer.sendSyncMessage(message);
            responseData.setCode(Code.Success);
        } catch (Exception e) {
            logger.info("pushAsyncMessage 异常", e);
            responseData.setMsg("消息推送失败");
            responseData.setCode(Code.Fail);
            return responseData;
        }
        logger.info("SendResult -> {}", ToStringBuilder.reflectionToString(responseData));
        return responseData;
    }
    /**
     * @Author huchenying
     * @Description 推送异步消息
     * @Date 2022/3/19 21:29
     **/
    @PostMapping("/pushAsyncMessageList")
    public ResponseData<SendResult> pushAsyncMessageList(@RequestBody MessageListRequestDTO message){
        logger.info("pushAsyncMessageList start param -> {}",ToStringBuilder.reflectionToString(message));
        ResponseData<SendResult> responseData = new ResponseData<>();
        try {
            asyncProducer.sendSyncMessageList(message.getMessageList());
        } catch (Exception e) {
            logger.info("pushAsyncMessage 异常", e);
            responseData.setMsg("消息推送失败");
            responseData.setCode(Code.Success);
            return responseData;
        }
        logger.info("SendResult -> {}", ToStringBuilder.reflectionToString(responseData));
        return responseData;
    }
}
